package com.pg_chat.service;

import com.pg_chat.config.YmlProperties;
import com.pg_chat.mapper.UserMapper;
import com.pg_chat.model.UserEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;

@Service("userService")
public class UserServiceImpl implements UserService{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    //Logger log = Logger.getLogger(UserServiceImpl.class);

    private final UserMapper userMapper;

    @Resource
    private YmlProperties ymlProperties;

    private HashMap<String,String> regexMap = null;


    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public boolean verify(String userName,String password){
        UserEntity user = null;
        try{
            user = userMapper.queryUserByName(userName);
            if(password.equals(user.getPassword()))
                return true;
        }catch (Exception e){
            if(user == null)
                logger.info("can't find the user for "+userName);
            else
                logger.warn("something happen!",e);
        }
        return false;
    }

    @Override
    public boolean verifyMD5(String userName,String password){
        return true;
    }

    @Override
    public boolean isAccountUsed(String account){
        return true;
    }

    @Override
    public UserEntity userMsgByName(String username) {
        UserEntity user = userMapper.queryUserByName(username);
        return user;
    }

    @Override
    public UserEntity userMsg(String account){
        UserEntity user = new UserEntity();
        return user;
    }



    @Override
    public HashMap<String, String> registerCheck(UserEntity user) {
        HashMap<String,String> resultMap = new HashMap<>();

        regexMap = ymlProperties.getValueRegex();

        String passwordRegex = regexMap.get("password");

        String phoneRegex = regexMap.get("phone");

        String emailRegex = regexMap.get("Email");

        if(!user.getPassword().matches(passwordRegex)){
            resultMap.put("password","invalid password");
        }
        if(user.getPhoneNumber() != null &&
                !user.getPhoneNumber().matches(phoneRegex))
            resultMap.put("phone","invalid phone");
        if(user.getEmailAddr() != null &&
                !user.getEmailAddr().matches(emailRegex))
            resultMap.put("Email","invalid Email");


        return resultMap;
    }

    @Override
    public boolean updateUserInfo(UserEntity user) {
        if (userMapper.updateUser(user) == 1){
            return true;
        }
        return false;
    }
}
